//
//  YZSearchFriendVC.m
//  VET
//
//  Created by lixiaoyi on 2018/7/13.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZSearchFriendVC.h"
#import "YZUser.h"
#import "ChatHeader.h"
#import "MJExtension.h"
#import "NSDictionary+Category.h"
#import "YZApplyFriendVC.h"
#import "YZNetworkConfig.h"
#import <WebKit/WebKit.h>

@interface YZSearchFriendVC ()<WKUIDelegate,WKNavigationDelegate>
@property (nonatomic, strong) WKWebView *webView;

@end

@implementation YZSearchFriendVC

#pragma mark - lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"添加好友";
    [self.view addSubview:self.webView];
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",[YZNetworkConfig getUrlCurrentDomain],@"/#/addfriend"];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    [self.webView loadRequest:request];
}

- (WKWebView *)webView {
    if (!_webView) {
        _webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
    }

    return _webView;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 打开导航
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    // 隐藏导航
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

#pragma mark - WKUIDelegate 拦截js的alert
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    NSLog(@"message------>%@",message);

    NSDictionary *functionObj = [NSDictionary dictionaryWithJsonString:message];
    NSString *functionStr = functionObj[@"action"];
    NSDictionary *data = functionObj[@"data"];
    if ([functionStr isEqualToString:@"getToken"]) {
        NSString *token = [YZUser sharedInstance].token;
        NSString *jsonStr = [@{@"token":token} TransToJSONString];
        [self.webView evaluateJavaScript:[NSString stringWithFormat:@"javascript:yz.native2js({callback:\"onGetToken\",data:%@})",jsonStr] completionHandler:^(id _Nullable response, NSError * _Nullable error) {
            if (!error) {
                NSLog(@"调用成功");
            }
        }];
    }else if ([functionStr isEqualToString:@"addFriend"]){
        // 添加好友
        NSString *uid = data[@"uid"];
        YZApplyFriendVC *applyFriendVC = [[YZApplyFriendVC alloc] init];
        applyFriendVC.targetId = uid;

        [self.navigationController pushViewController:applyFriendVC animated:YES];

    }

    completionHandler();
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
